package cn.wolfcode.luowowo.website.resolver;

//import cn.wolfcode.luowowo.cache.service.IUserInfoCacheService;
import cn.wolfcode.luowowo.cache.service.IUserInfoCacheService;
import cn.wolfcode.luowowo.common.util.Consts;
import cn.wolfcode.luowowo.member.domain.UserInfo;
//import cn.wolfcode.luowowo.website.annotion.LoginUser;
import cn.wolfcode.luowowo.website.annotation.LoginUser;
import com.alibaba.fastjson.JSON;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Component
public class UserInfoArgumentResolver
        implements HandlerMethodArgumentResolver {
    @Reference
    private IUserInfoCacheService userInfoCacheService;

    public boolean supportsParameter(MethodParameter parameter) {
        return UserInfo.class.equals(parameter.getParameterType()) &&
               parameter.hasParameterAnnotation(LoginUser.class);
    }

    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest, WebDataBinderFactory binderFactory)
            throws Exception {
        HttpServletRequest req = webRequest.getNativeRequest(HttpServletRequest.class);
        HttpSession session = req.getSession();
        Object userInfo = session.getAttribute(Consts.USER_INFO);
        if (userInfo != null) {
            return userInfo;
        }

        Cookie[] cs = req.getCookies();
        if (cs != null) {
            for (Cookie cookie : cs) {
                if (cookie.getName().equals(Consts.USER_INFO_TOKEN)) {
                    String token = cookie.getValue();
                    String cacheVale = userInfoCacheService.getUserInfo(token);
                    if (cacheVale != null) {
                        userInfo = JSON.parseObject(cacheVale, UserInfo.class);
                        session.setAttribute(Consts.USER_INFO, userInfo);
                        return userInfo;
                    }
                    break;
                }
            }
        }
        return null;
    }
}
